﻿using EONFULLSIN.Models.Entity.Log;
using NLog;
using System;

namespace EONFULLSIN.Utils
{
    public class LoggerHelper
    {
        public static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="loggerName">警告类或方法名</param>
        /// <param name="message">消息正文</param>
        public static void Info(string deviceType, string loggerName, string message)
        {
            var logEvent = new LogEventInfo(LogLevel.Info, loggerName, message);
            logEvent.Properties["deviceType"] = deviceType;
            InsertLogAsync(LogLevel.Info, deviceType, loggerName, message);
            Logger.Log(logEvent);
        }

        /// <summary>
        /// 警告
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="loggerName">警告类或方法名</param>
        /// <param name="message">消息正文</param>
        public static void Warn(string deviceType, string loggerName, string message)
        {
            var logEvent = new LogEventInfo(LogLevel.Warn, loggerName, message);
            logEvent.Properties["deviceType"] = deviceType;
            InsertLogAsync(LogLevel.Warn, deviceType, loggerName, message);

            Logger.Log(logEvent);
        }

        /// <summary>
        /// 错误
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="loggerName">警告类或方法名</param>
        /// <param name="message">消息正文</param>
        public static void Error(string deviceType, string loggerName, string message)
        {
            var logEvent = new LogEventInfo(LogLevel.Error, loggerName, message);
            logEvent.Properties["deviceType"] = deviceType;
            InsertLogAsync(LogLevel.Error, deviceType, loggerName, message);

            Logger.Log(logEvent);
        }

        public static async void InsertLogAsync(LogLevel logLevel, string deviceType, string loggerName, string message)
        {
            LogRecord logRecord = new LogRecord()
            {
                DeviceType = deviceType,
                Level = nameof(logLevel),
                Logger = loggerName,
                Message = message,
                Date = DateTime.Now,
                IsDeleted = false
            };
            await DBHelper.HistoryDbContext.Insert(logRecord).ExecuteInsertedAsync();
        }
    }
}